<!DOCTYPE html>
<html>
<head>
	<meta charset:"utf-8"/> 
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no"> 

	<title>Bootstrap 实例 - 下拉菜单（Dropdowns）</title>
	
        <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
       <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">  
  
<!-- 可选的Bootstrap主题文件（一般不使用） -->

 
<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
 <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script> 
 
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
 <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
		<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
		

<!-- <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.css"> -->

<!-- Latest compiled and minified JavaScript -->
<!-- <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.js"></script> -->

<!-- Latest compiled and minified Locales -->
<!-- <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/locale/bootstrap-table-zh-CN.min.js"></script> -->


         <!-- bootstrap-table -->
    <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=8ea516fb9ce8a92d0e8f20fd1d2c28f0"></script>  
	</head>
  <body>
 
<table id="table" ></table>
<div id="container" style="width:800px; height:800px"></div>
<div id="model2"></div>
<button id='zxx' >1111</button>     
</body>
<script>
var Model = {
	createNew:function($model={}){
		var model = {};
		model.jqobj = $model;
		model.style = {
			Project:{
				header:'项目',
				labels:['Name','ID','CountyID'],
				buttons:['add','del','wee'],
				event:{
					add:function(){
						console.log('rrrrr');
					},
					del:function(){
						console.log('del it');
					},
					wee:function(){
						console.log('del itttt');
					}
				},
				translator:{
					ID:'项目编号',
				},
			},
			Concentrator:{
				header:'集中器',
				labels:['Name','ID'],
				buttons:['add','del'],
				event:{
					add:function(){
						console.log(111);
					},
					del:function(){
						console.log('del it');
					}
				},
				translator:{

				},
			},
			Controller:{
				header:'kzq',
				labels:['Name','ID'],
				buttons:['add','del'],
				event:{
					add:function(){
						console.log(111);
					},
					del:function(){
						console.log('del it');
					}
				},
				translator:{

				},
			},
			lineConcentrator:{
				header:'kzqqqqq',
				labels:['Name','ID'],
				buttons:['add','del'],
				event:{
					add:function(){
						console.log('add it');
					},
					del:function(){
						console.log('del it');
					}
				},
				translator:{

				},
			}

		}
		model.translator={
			ID:'编号',
			Number:'短编号',
			Name:'名称',
			Longitude:'经度',
			Laitude:'纬度',
			RenewTime:'安装/更新时间',
			Remarks:'备注',
			Location:'地点',

			ConcentratorID:'集中器编号',
			ControllerAmount:'控制器数量'  ,
			CollectTime:'采集时间',
			PartsEnableState:'部件使能状态', 
			CircuitState:'回路状态',
			Illuminance:'照度值',
			Fault:'故障',
			TotalPower:'总电能', 
			APhaseVolt:'A相电压',
			BPhaseVolt:'B相电压',
			CPhaseVolt:'C相电压',
			ABPhaseCurrent:'A相电流', 
			BCPhaseCurrent:'B相电流',
			ACPhaseCurrent:'C相电流',  

			ControllerID:'控制器编号',
			Lumalevel   :'亮度级别',
			Current   :'电流',
			Voltage   :'电压',


			ContactPersonID:'联系人' ,
			CountyID:  '地址',
			CreateTime:  '创建时间',
		};
		model.init = function(type,row){
			model.jqobj.html(model.getModelHtml(type,row));
			$('.close').click(function(){
				$(this).parent().parent().hide();
			})
			model.style[type].buttons.forEach(function(button) {
				if(button in model.style[type].event){
					$('#' + button).click(function(){
						model.style[type].event[button]();
					});
				};
			}, this);
		};
		model.getModelHtml = function (type,row={}) {
			var contentBegin = 
			`<div class="modal-dialog" style="width:600px ;left:30%;top:25%;position:absolute;z-index:999;">  
			<div class="modal-content" style="background-color:#B0C4DE;">`
			var contentEnd = `</div></div>`;
			var headerHtml = 
			`<div class="modal-header" style="width:100%;height:50px;">  
            	<button id="clo" type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> 
            	<h4 class="modal-title">${model.style[type].header}</h4>   
			</div>  `;
			var bodyBegin = 
			`<div class="modal-body" style="width:100%;height:380px;">  
            <div class="col-md-10 column" >
			<div class="form-horizontal" role="form">`;
			var bodyEnd = '</div></div></div>';
			return contentBegin + headerHtml + bodyBegin + model.getLabelsHtml(type,row) + model.getButtonHtml(type) + bodyEnd + contentEnd;
		}
		model.getLabelsHtml = function(type,row){
			var result = '';
			model.style[type].labels.forEach(function(label) {
				var labelname = '';
				if(label in model.style[type].translator){
					labelname = model.style[type].translator[label];
				}
				else{
					labelname = label;
				}
				var value = '';
				if(label in row){
					value = row[label];
				}
				var labelHtml =
				`<div class="form-group">
					<label class="col-sm-4 control-label">${labelname}</label>
					<div class="col-sm-8">
						<input type="text" class="form-control"  name=${label} value=${value} />
					</div>
				</div>`;
				result = result + labelHtml;
			}, this);
			return result;
		};

		model.getButtonHtml = function(type){
			var result = '<div class="form-group">';
			model.style[type].buttons.forEach(function(button) {
				var buttonname = '';
				if(buttonname in model.translator){
					buttonname = model.translator[label];
				}
				else{
					buttonname = button;
				}
				var buttonHtml =
				`<div class="col-sm-offset-2 col-sm-10">
              	<button id=${button} class="btn btn btn-s-md btn-default btn-rounded">${buttonname}</button>  
            	</div>`;
				result = result + buttonHtml;
			}, this);
			return result + '</div>';
		};
		return model;
	}
}


///////////////////////////////////////////////////////////////////////////////////////
var Map = {
	createNew:function(amap={}){
		if(amap == {}){
			return {};
		}
		var map = {};
		//全局常量设置
		map.CONTROLLER = 'Controller';
		map.CONCENTRATOR = 'Concentrator';
		map.PROJECT = 'Project';

		map.option = {
			projectSearch:'',
			concentratorSearch:'',
			controllersearch:'',
			type:'',
			//定时器id
			intervalID:-99,
			//显示键值设置
			
		};
		map.style = {
			Default:{
				titleStyle:[
					'ID' ,
				],
				menuStyle:[
					{
						item:'xxxxxxxx',
						event:function (marker) {
						},
						index:0,
					},
					{
						item:'xxxxxxxxxxx',
						event:function(){
						},
						index:1,
					},
				],
				lineStyle:{
					strokeColor: "#FF0000", //线颜色
					strokeOpacity: 1,       //线透明度
					strokeWeight: 20,        //线宽
					strokeStyle: "dashed",   //线样式
					strokeDasharray: [10, 10], //补充线样式
				},
				iconStyle:function(row){
					return 'Default';
				},
			},
			Concentrator:{
				titleStyle:[
					'ID' ,
					//'ConcentratorID' ,
					'ControllerAmount' ,
					'CollectTime' ,
					'Longitude' ,
					'Laitude' ,
					'PartsEnableState', 
					'CircuitState' ,
					'Illuminance' ,
					'Fault' ,
					'TotalPower', 
					'APhaseVolt' ,
					'BPhaseVolt' ,
					'CPhaseVolt' ,
					'ABPhaseCurrent', 
					'BCPhaseCurrent' ,
					'ACPhaseCurrent' 
				],
				menuStyle:[
					{
						item:'设置',
						event:function (marker) {
							row = map.doAjax('get','Concentrator',{ID:marker.getExtData().id})['rows'][0];
							var m = Model.createNew($('#model2'));
							m.init('Concentrator',row);
						},
						index:0,
					},
					{
						item:'sxx',
						event:function(){
						},
						index:1,
					},
				],
				lineStyle:{
					strokeColor: "#FF00FF", //线颜色
					strokeOpacity: 1,       //线透明度
					strokeWeight: 8,        //线宽
					strokeStyle: "dashed",   //线样式
					strokeDasharray: [10, 10], //补充线样式
				},
				iconStyle:function(row){
					if (row.Fault == 255) {
						return'ConcentratorOn';
					}
					else{
						return'ConcentratorAlarm';
					}
				},
				translator:{
					ID:'编号',
					ControllerAmount:'控制器数量'  ,
					CollectTime:'采集时间',
					PartsEnableState:'部件使能状态', 
					CircuitState:'回路状态',
					Illuminance:'照度值',
					Fault:'故障',
					TotalPower:'总电能', 
					APhaseVolt:'A相电压',
					BPhaseVolt:'B相电压',
					CPhaseVolt:'C相电压',
					ABPhaseCurrent:'A相电流', 
					BCPhaseCurrent:'B相电流',
					ACPhaseCurrent:'C相电流',
					Longitude:'经度',
					Laitude:'纬度',
				},
				
			},

			Project:{
				titleStyle:[
					'ID' ,
					'Name' ,
					'ContactPersonID' ,
					'CountyID' ,
					'CreateTime' ,
				],
				menuStyle:[
					{
						item:'设置',
						event:function (marker) {
							row = map.doAjax('get','Project',{ID:marker.getExtData().id})['rows'][0];
							var m = Model.createNew($('#model2'));
							m.init(map.PROJECT,row);
						},
						index:0,
					},
					{
						item:'sxx',
						event:function(){
						},
						index:1,
					},
				],
				lineStyle:{
					strokeColor: "#3366FF", //线颜色
					strokeOpacity: 1,       //线透明度
					strokeWeight: 3,        //线宽
					strokeStyle: "dashed",   //线样式
					strokeDasharray: [10, 10], //补充线样式
				},
				iconStyle:function(row){
					return 'Project';
				},
				translator:{
					ID:'项目编号',
					Name:'名称',
					ContactPersonID:'联系人' ,
					CountyID:'地址',
					CreateTime:'创建时间',
				}
			},


			Controller:{
				titleStyle:[
					'ID' ,
					//'ControllerID' ,
					'Lumalevel' ,
					'Current' ,
					'Voltage' ,
					'CollectTime' ,
					'Fault' 
				],
				menuStyle:[
					{
						item:'设置',
						event:function (marker) {
							row = map.doAjax('get','Mcontroller',{ID:marker.getExtData().id})['rows'][0];
							var m = Model.createNew($('#model2'));
							m.init('Controller',row);
						},
						index:0,
					},
					{
						item:'sxx',
						event:function(){
						},
						index:1,
					},
				],
				lineStyle:{
					strokeColor: "#FF00FF", //线颜色
					strokeOpacity: 1,       //线透明度
					strokeWeight: 3,        //线宽
					strokeStyle: "dashed",   //线样式
					strokeDasharray: [5, 10], //补充线样式
				},
				iconStyle:function(row){
					if (row.Fault == 255) {
						if(row.Lumalevel == 0){
							return'LampOff';
						}
						else{
							return'LampOn'
						}
					}
					else{
						return'LampAlarm';
					}
				},
				translator:{
					ID:'编号',
					Name:'名称',
					Fault:'故障',
					Lumalevel:'亮度级别',
					Current:'电流',
					Voltage:'电压',
					CollectTime:'采集时间',
				},
			}



		}
		////////////////////////////////////////////////////////////////////////////////////////////
		map.amap = amap;
		map.markers = [];
		///////////////////////////////////////////////////////////数据转换区
		map.createMarker = function(options={}){
			return new AMap.Marker(options);
		}

		map.doAjax = function(type,url,data){
			var y;
			$.ajax({  
				type : type,  
		        url : '/tp5/public/index/'+url+'/'+url,  
		        data :data,  
		        async : false,  
				contentType:'application/x-www-form-urlencoded',
		        success : function(result){  
					y = result;
		        }
    		});  
    		return y;
		};

		map.row2str = function(type,row){  //如果翻译未翻译，则使用英文单词 参数titleStyle translator，default为输出全部
			var str ='';
			if(type in map.style){
				var obj = map.style[type];
				obj.titleStyle.forEach(function(element) {
					if(element in obj.translator){
						str = str + obj.translator[element]+':'+row[element] +'\n';
					}
					else{
						str = str + element + ':' + row[element] + '\n';
					}
					
				}, this);
			}
			else{
				var obj = map.style['Default'];
				obj.titleStyle.forEach(function(element) {
					str = str + element + ':' + row[element] + '\n';
				}, this);
			}
			return str;
		};
		
		map.row2IconType = function(type,row){  //图标表写在iconStyle里
			if(type in map.style){
				return map.style[type].iconStyle(row);
			}
			else{
				return map.style['Default'].iconStyle(row);
			}
			
		}
///////////////////////////////////////////////////////////////////////////////添加组件
		map.addMarkers = function(rows,type){
			if(rows.length==0){
				return 0;
			}
			for (var i = 0; i < rows.length; i++) {
				var row = rows[i];
				var p = {
						position:[row['Longitude'],row['Laitude']],
						title:map.row2str(type,row),
						icon:new AMap.Icon({ 
							size:[36,36],
            				image: "/tp5/public/static/img/" + map.row2IconType(type,row) +'.ico',			
						})
				};
				var marker = map.createMarker(p);
				marker.setExtData({type:type,id:row['ID']});
				marker.on('rightclick',function(e){
					map.set(e,this);
				});
				marker.on('click',function(e){
					map.spread(e,this);
				});
				marker.setMap(map.amap);
				
				
			}
		};
		map.addPolyline = function(rows,type){   //用线连接，参数设置map.lineStyle
			var style = {};
			if(type in map.style){
				style = map.style[type].lineStyle;
			}
			else{
				style = map.style['Default'].lineStyle;
			}
			style['path'] = [];
			rows.forEach(function(row) {
				var position = [row['Longitude'],row['Laitude']];
				style['path'].push(position);
			}, this);
			var polyline = new AMap.Polyline(style);
			var id = '';
			if(type === map.CONCENTRATOR){
				id = rows[0].RouteID;
			}
			if(type === map.CONTROLLER){
				id = rows[0].GroupID;
			}
			polyline.setExtData({type:'line' + type,id:id});
			polyline.on('click',function(e){
				map.lineSet(e,this);
			});
			polyline.setMap(map.amap);
		}
		map.addContextMenu = function (e, marker) {
			var type = marker.getExtData().type;
			var contextMenu = new AMap.ContextMenu();
			if (type in map.style) {
					map.style[type].menuStyle.forEach(function(element) {
					var	event = element.event
					contextMenu.addItem(element.item, function(e){
						element.event(marker);
					}, element.index);
				}, this);
			}
			else{
				map.style['Default'].menuStyle.forEach(function(element) {
					contextMenu.addItem(element.item, element.event, element.index);
				}, this);
			}
			contextMenu.open(map.amap, e.lnglat);
		}
		//////////////////////////////////////////////////////////////////////事件代码区
		map.spread = function(e,marker){     //marker左击
			var type = marker.getExtData().type;
			var id = marker.getExtData().id;
			if (type === map.PROJECT) {
				map.amap.clearMap();
				map.drawProjectDetail({ID:id});
			}
			if (type === map.CONCENTRATOR) {
				map.amap.clearMap();
				map.option.concentratorSearch = {ID:id};
				map.drawConcentratorDetail({ID:id});
			}
		}
		map.set = function (e,marker) {     //marker右击
			map.addContextMenu(e,marker);
		}
		map.lineSet = function (e,line) {
			map.addContextMenu(e,line);
		}
		////////////////////////////////////////////////////////////////////////////////接口区
		map.draw = function(rows,type,polyFlag=true){
			map.addMarkers(rows,type);
			if(polyFlag){
				map.addPolyline(rows,type)
			}
			map.amap.setFitView();
		}

		map.drawProject = function (search={}) {
			search['withPosition'] = 1;
			var rows = map.doAjax('get','Project',search).rows;
			if(rows.length == 0){
				return;
			}
			map.draw(rows,map.PROJECT,false);
		}
		map.drawProjectDetail = function(search={}){
			search['project'] = 1;
			search['Days'] = '-100 days';
			var rows = map.doAjax('get','Concentratorstate',search).rows;
			var routes = {};
			rows.forEach(function(row) {
				var routeid = row.RouteID + '';
				if(routeid in routes){
					routes[routeid].push(row);
				}
				else{
					routes[routeid] = [];
					routes[routeid].push(row);
				}
			}, this);
			for (var key in routes) {
				var rows = routes[key];
				map.draw(rows,map.CONCENTRATOR,true);
			}
		}
		map.drawConcentratorDetail = function(search={}){
			search['concentrator'] = 1;
			search['Days'] = '-100 days';
			var rows = map.doAjax('get','controllerstate',search).rows;
			var  groups = {};
			rows.forEach(function(row) {
				var groupid = row.GroupID + '';
				if( groupid in groups){
					 groups[groupid].push(row);
				}
				else{
					 groups[groupid] = [];
					 groups[groupid].push(row);
				}
			}, this);
			for (var key in  groups) {
				var rows =  groups[key];
				map.draw(rows,map.CONTROLLER,true);
			}
		}
		
		//初始化地图
		map.init = function(url,data,clearflag=true){
			map.drawProject();
			var contextMenu = new AMap.ContextMenu();
			contextMenu.addItem("返回到项目", function() {
				map.amap.clearMap();
				map.drawProject({position:1});
			}, 0);
			contextMenu.addItem("返回到集中器", function() {
				if(map.option.concentratorSearch != ''){
					map.amap.clearMap();
					map.drawProjectDetail(map.option.concentratorSearch);
					console.log(1111);
				}
			}, 1);
			contextMenu.addItem("返回到集中器2", function() {
				contextMenu.removeItem(1);
			}, 2);
			map.amap.on('rightclick', function(e) {
				contextMenu.open(map.amap, e.lnglat);
				
    		});
		}
		map.startInterval = function(ms){   /*开始定时器*/
			if (map.option.url =='') {
				console.log('没有配置url');
				return;
			}
			if (map.option.data =='') {
				console.log('没有配置data');
				return;
			}
			map.option.intervalID = setInterval(function(){
				map.updateMarkers();
			},ms);
		}
		map.stopInterval = function(){   /*关闭定时器*/
			if(map.option.intervalID == -99){
				console.log('先startInterval才能stop');
				return;
			}
			clearInterval(map.option.intervalID);
			map.option.intervalID = -99;
		}
		return map;
	}
}






$(function () {
	// 说明
	// 1.生成高德map对象
	// 2.传入高德map对象
	// 3.初始化 获取数据的设置
	// 4.设置 定时间隔（可选）    定时的使用，start只能使用一次，想再使用，必须先stop.然后再start.
	// 5.关闭 定时（可选）
	var map = new AMap.Map('container', {
		resizeEnable: true,
		zoom:14,
		center: [113.397428, 39.90923]
	});
	var tmap = Map.createNew(map);
	tmap.init({position:1});
	// tmap.startInterval(3500);
	//tmap.stopInterval();
	
	// var data = {};
	// data.data = [];
	// for (var i = 0; i < 100; i++) {
	// 	// tmap.doAjax('post','Mcontroall',{data:[
	// 	// 	{ ID:123+i ,  Number:i%500 ,  Name:'zvx' ,  Longitude:113.947342+i*0.001 ,  Laitude:28.456478 ,  TypeID:1 ,  LampTypeID:1 ,  RouteID:1 ,  ConcentratorID:1 ,  ConcentratorCircuitID:1 ,  ConcentratorCircuitGroupID:1 ,  RenewTime:'2017-07-25 00:00:00' ,  Remarks:'sasas' ,  Location:'南京' }
	// 	// ]})
	// 	one = {
	// 	// ConcentratorID:323+parseInt(i/10) , 
	// 	// ControllerAmount:200 ,
	// 	// CollectTime:'2017-7-23 09:01:0'+i%10, 
	// 	// Longitude:(113.947342+i*0.01).toFixed(6)*1 , 
	// 	// Laitude:28.456478.toFixed(6)*1 , 
	// 	// PartsEnableState:1,
	// 	// CircuitState:1,
	// 	// Illuminance:10,
	// 	// Fault:1,
	// 	// TotalPower:23.56,
	// 	// APhaseVolt  :2.5,
	// 	// BPhaseVolt :2.5,
	// 	// CPhaseVolt  :2.5,
	// 	// ABPhaseCurrent :2.5, 
	// 	// BCPhaseCurrent  :2.5,
	// 	// ACPhaseCurrent :2.5 ,

	// 	// ID:1+i,
	// 	// Number:12,  
	// 	// Name  :'zxxw',
	// 	// Longitude:(113.947342+i*0.01).toFixed(6)*1,  
	// 	// Laitude:28.456478.toFixed(6)*1,   
	// 	// TypeID  :1, 
	// 	// LampTypeID:1,  
	// 	// RouteID   :1,
	// 	// ConcentratorID :1,  
	// 	// ConcentratorCircuitID :1, 
	// 	// ConcentratorCircuitGroupID:1,  
	// 	// RenewTime  :'2017-3-4 09:09:09',
	// 	// Remarks  :'xxxxx',
	// 	// Location  :'ccccc',

	// var table = Table.createNew($('#table'));
	// table.initFrame('Project',{limit:10,offset:0});
	// table.gotoPage(1);

		
	//返回true/false = 位置是否改变
		//根据获得数据更新单一marker
		// map.updateMarker = function(marker,rows){
		// 	for (var i = 0; i < rows.length; i++) {
		// 		var element = rows[i];
		// 		if(marker.getExtData().ID==element.ID){
		// 			var position = marker.getPosition();
		// 			if (position.getLng() == parseFloat(element['Longitude'])&&position.getLat() == parseFloat(element['Laitude'])) {
						
		// 				if(marker.getExtData().Fault != element.Fault){
		// 					marker.setIcon(
		// 						new AMap.Icon({ 
		// 							size:[36,36],
		// 							image: "/tp5/public/static/img/" + map.row2IconType(element) +'.ico',			
		// 						})
		// 					);
		// 				}
		// 				marker.setTitle(map.row2str(map.option.url,element));
		// 				return {flag:false,rowIndex:i};
		// 			}
		// 			else{
		// 				marker.setPosition([element['Longitude'],element['Laitude']]);
		// 				if(marker.getExtData().Fault != element.Fault){
		// 					marker.setIcon(
		// 						new AMap.Icon({ 
		// 							size:[36,36],
		// 							image: "/tp5/public/static/img/" + map.row2IconType(element) +'.ico',			
		// 						})
		// 					);
		// 				}
		// 				marker.setTitle(map.row2str(map.option.url,element));
		// 				return {flag:true,rowIndex:i};
		// 			}
		// 		}
		// 	}
		// 	marker.setMap(null);
		// 	return {flag:true,rowIndex:-1};
		// }
		// //根据获得数据来更新所有marker
		// map.updateMarkers = function(markers=[],rows=[]){
		// 	if(markers.length == 0){
		// 		markers = map.amap.getAllOverlays('marker');
		// 	}
		// 	if(rows.length == 0){ /*自己获得数据，如果没数据传入*/
		// 		rows = map.doAjax('get',map.option.url,map.option.data).rows
		// 	}
		// 	var setFitViewFlag = false;
		// 	var extraRows = rows;
		// 	for (var i = 0; i < markers.length; i++) {
		// 		var marker = markers[i];
		// 		result = map.updateMarker(marker,rows);
		// 		if(!setFitViewFlag){
		// 			setFitViewFlag = result.flag;
		// 		}
		// 		index = result.rowIndex;
		// 		if (index!=-1) {
		// 			extraRows.splice(index,1);
		// 		}
		// 	}
		// 	map.addMarkers(map.rows2oparray(extraRows,map.option.url));
		// 	if(extraRows.length > 0){
		// 		setFitViewFlag = true;
		// 	}
		// 	if(setFitViewFlag){
		// 		map.amap.setFitView();
		// 	}
		// }
	
});
	
 
 

 
 
</script>  
</html> 
